package cn.tedu.eg_user.controller;

import cn.tedu.eg_user.base.response.JsonResult;
import cn.tedu.eg_user.base.response.StatusCode;
import cn.tedu.eg_user.mapper.UserMapper;
import cn.tedu.eg_user.pojo.dto.UserAddParam;
import cn.tedu.eg_user.pojo.dto.UserUpdateParam;
import cn.tedu.eg_user.pojo.entity.User;
import cn.tedu.eg_user.pojo.vo.UserListVO;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
@Validated
@Slf4j
@RestController
@Tag(name="用户模块")
@RequestMapping("/v1/user/")

public class UserController {

    @Autowired
    private UserMapper userMapper;
    @PostMapping("add")
    @Operation(summary="添加用户")
    @ApiOperationSupport(order=10)
    public JsonResult addUser(@RequestBody @Validated UserAddParam param){
        User user=new User();
        BeanUtils.copyProperties(param, user);
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        userMapper.insertUserById(user);
        return new JsonResult(StatusCode.UPERATION_SUCCESS);
    }

    @GetMapping("list")
    @Operation(summary="用户列表")
    @ApiOperationSupport(order=20)
    public JsonResult userListVOs(){
        List<UserListVO> userList=userMapper.userListVOS();
        return new JsonResult(StatusCode.UPERATION_SUCCESS, userList);
    }


    @PostMapping ("del/{id}")
    @Operation(summary="删除用户")
    @ApiOperationSupport(order=30)
    @Parameter(name="id")
    public JsonResult delUser(@PathVariable @Range(min=1L,max =100L,message="用户id必须在1-100之间") Long id){
        System.out.println("id:"+id);
        int rows=userMapper.deleteUserById(id);
        if (rows>0){
            return new JsonResult(StatusCode.UPERATION_SUCCESS);
        }else {
            return new JsonResult(StatusCode.OPERATION_FAILED);
        }
    }

    @PostMapping("update")
    @Operation(summary="更新用户")
    @ApiOperationSupport(order=40)
    public JsonResult updUserById(@RequestBody UserUpdateParam param){
        System.out.println("param:"+param);
      User user =new User();
      BeanUtils.copyProperties(param, user);
      user.setUpdateTime(new Date());
      int rows=userMapper.updateUserId(user);
      if (rows>0){
          return new JsonResult(StatusCode.UPERATION_SUCCESS);
      }else {
          return new JsonResult(StatusCode.OPERATION_FAILED);
      }
    }




}
